package com.huilian.iotbox.data.service.impl;

import com.alibaba.fastjson.JSON;
import com.huilian.iotbox.data.dao.MemberCommonDao;
import com.huilian.iotbox.data.dto.MemberDto;
import com.huilian.iotbox.data.dto.MemberStoreBalanceDto;
import com.huilian.iotbox.data.dto.MerchantStoreDto;
import com.huilian.iotbox.data.po.Member;
import com.huilian.iotbox.data.po.MemberStoreBalance;
import com.huilian.iotbox.data.po.TicketRecord;
import com.huilian.iotbox.data.service.*;
import com.huilian.iotbox.data.vo.MemberStoreBalanceVo;
import com.huilian.iotbox.data.vo.MerchantStoreVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class MemberCommonServiceImpl implements MemberCommonService {

    @Autowired
    private ErrorLogCommonService errorLogCommonService;
    @Autowired
    private MemberCommonDao memberCommonDao;
    @Autowired
    private MerchantStoreCommonService merchantStoreCommonService;
    @Autowired
    private MemberStoreBalanceCommonService memberStoreBalanceCommonService;

    @Override
    public Long mergeMemberInfo(List<Member> memberList, MemberDto memberDto, String mobile) {
        /**检查手机号重复的会员-begin*/

        log.info("检查手机号重复的会员-begin");
        log.info("memberList:{}", JSON.toJSONString(memberList));
        log.info("memberDto:{}", JSON.toJSONString(memberDto));
        log.info("mobile:{}", mobile);
        Integer currIndex = null;
        for (int i = 0; i < memberList.size(); i++) {
            if (memberList.get(i).getId().compareTo(memberDto.getId()) == 0) {
                currIndex = i;
                break;
            }
        }

        if (!StringUtils.isEmpty(currIndex)) {
            // 删除失败最大重试次数
            int retryCount = 5;
            boolean removeResult = false;
            do {
                removeResult = memberList.remove(currIndex);
            } while (!removeResult && retryCount-- > 0);

            if (!removeResult) {
                errorLogCommonService.writerInfoErrorLog("合并失败，请联系商家和平台处理", memberList);
                throw new RuntimeException("合并失败，请联系商家和平台处理");
            }
        }

        if (memberList.size() >= 2) {
            // 剔除当前会员信息，发现超过1个相同手机号的账号就默认合并不成功
            errorLogCommonService.writerInfoErrorLog("合并失败，请联系商家和平台处理。问题：发现超过1个相同手机号的账号", memberList);
            throw new RuntimeException("合并失败，请联系商家和平台处理。问题：发现超过1个相同手机号的账号");
        }

        // 当前登录会员
        MemberDto currMember = memberCommonDao.queryById(memberDto.getId());
        // 同手机号会员
        Member member = memberList.get(0);

        if (!StringUtils.isEmpty(currMember.getUnionId()) && !StringUtils.isEmpty(member.getUnionId())) {
            // 都是微信，不可以合并。可能是旧微信跟新微信同手机号
            errorLogCommonService.writerInfoErrorLog("合并失败，请联系商家和平台处理。问题：相同手机号的账号都为微信账号", currMember);
            throw new RuntimeException("合并失败，请联系商家和平台处理。问题：相同手机号的账号都为微信账号");
        }

        if (!StringUtils.isEmpty(currMember.getZfbUnionId()) && !StringUtils.isEmpty(member.getZfbUnionId())) {
            // 都是支付宝，不可以合并。可能是旧支付宝跟新支付宝同手机号
            errorLogCommonService.writerInfoErrorLog("合并失败，请联系商家和平台处理。问题：相同手机号的账号都为支付宝账号", currMember);
            throw new RuntimeException("合并失败，请联系商家和平台处理。问题：相同手机号的账号都为支付宝账号");
        }

        if (!StringUtils.isEmpty(currMember.getTtUnionId()) && !StringUtils.isEmpty(member.getTtUnionId())) {
            // 都是抖音，不可以合并。可能是旧抖音跟新抖音同手机号
            errorLogCommonService.writerInfoErrorLog("合并失败，请联系商家和平台处理。问题：相同手机号的账号都为抖音账号", currMember);
            throw new RuntimeException("合并失败，请联系商家和平台处理。问题：相同手机号的账号都为抖音账号");
        }
        /**检查手机号重复的会员-end*/

        /**
         *
         * 手机号唯一
         * 将原member_store_balance
         *
         * member_store_balance
         */

        /**将手机号重复的会员合并到当前登录的会员并将member_store_balance的累加-begin*/
        List<MemberStoreBalance> memberStoreBalanceList = memberStoreBalanceCommonService.findAllByMemberId(member.getId());
        for (MemberStoreBalance memberStoreBalance : memberStoreBalanceList) {
            MerchantStoreDto merchantStoreDto = new MerchantStoreDto();
            merchantStoreDto.setId(memberStoreBalance.getMerchantStoreId());
            MerchantStoreVo merchantStoreVo = merchantStoreCommonService.findOneMerchantStoreByCondition(merchantStoreDto);

            // 查询新会员主体是否有余额记录
            MemberStoreBalanceDto memberStoreBalanceDto = new MemberStoreBalanceDto();
            memberStoreBalanceDto.setMerchantStoreId(memberStoreBalance.getMerchantStoreId());
            memberStoreBalanceDto.setMemberId(currMember.getId());
            MemberStoreBalanceVo memberStoreBalanceVo = memberStoreBalanceCommonService.findBalance(memberStoreBalanceDto);
            if (StringUtils.isEmpty(memberStoreBalanceVo)) {
                memberStoreBalanceCommonService.add(currMember.getId(), memberStoreBalance.getMerchantStoreId(), merchantStoreVo.getUserId(), null);
                memberStoreBalanceVo = memberStoreBalanceCommonService.findBalance(memberStoreBalanceDto);
            }

            // 余额累加
            if (memberStoreBalance.getMoneyRechargeBalance().compareTo(BigDecimal.ZERO) == 1 || memberStoreBalance.getMoneyDonateBalance().compareTo(BigDecimal.ZERO) == 1) {
                log.info("memberStoreBalance.getMoneyRechargeBalance()" + memberStoreBalance.getMoneyRechargeBalance());
                log.info("memberStoreBalance.getMoneyDonateBalance()" + memberStoreBalance.getMoneyDonateBalance());
                MemberStoreBalance updateMemberStoreBalance = new MemberStoreBalance();
                updateMemberStoreBalance.setId(memberStoreBalanceVo.getId());
                updateMemberStoreBalance.setMoneyRechargeBalance(memberStoreBalance.getMoneyRechargeBalance());
                updateMemberStoreBalance.setMoneyDonateBalance(memberStoreBalance.getMoneyDonateBalance());
                updateMemberStoreBalance.setMemberId(memberStoreBalanceVo.getMemberId());
                updateMemberStoreBalance.setUserId(merchantStoreVo.getUserId());
                updateMemberStoreBalance.setMerchantStoreId(memberStoreBalance.getMerchantStoreId());
                log.info("updateMemberStoreBalance.setMoneyRechargeBalance" + updateMemberStoreBalance.getMoneyRechargeBalance());
                log.info("updateMemberStoreBalance.setMoneyDonateBalance" + updateMemberStoreBalance.getMoneyDonateBalance());
                memberStoreBalanceCommonService.addMemberStoreMoneyBalance(
                        1,
                        updateMemberStoreBalance
                );
            }

            // 游戏币累加
            if (memberStoreBalance.getRechargeBalance() > 0 || memberStoreBalance.getDonateBalance() > 0) {
                memberStoreBalanceCommonService.addMemberStoreBalance(
                        1,
                        memberStoreBalance.getRechargeBalance(),
                        memberStoreBalance.getDonateBalance(),
                        memberStoreBalanceVo.getId(),
                        memberStoreBalanceVo.getMemberId(),
                        merchantStoreVo.getUserId(),
                        memberStoreBalance.getMerchantStoreId()
                );
            }

            // 积分累加
            if (memberStoreBalance.getIntegral() > 0) {
                memberStoreBalanceCommonService.addMemberStoreIntegralBalance(
                        1,
                        memberStoreBalance.getIntegral(),
                        memberStoreBalanceVo.getId(),
                        memberStoreBalanceVo.getMemberId(),
                        merchantStoreVo.getUserId(),
                        memberStoreBalance.getMerchantStoreId()
                );
            }

            // 彩票累加
            if (memberStoreBalance.getLottery() > 0) {
                memberStoreBalanceCommonService.addMemberStoreLotteryBalance(
                        1,
                        memberStoreBalance.getLottery(),
                        memberStoreBalanceVo.getId(),
                        memberStoreBalanceVo.getMemberId(),
                        merchantStoreVo.getUserId(),
                        memberStoreBalance.getMerchantStoreId()
                );
            }

            // 累计支付金额
            if (memberStoreBalance.getTotalPay().compareTo(BigDecimal.ZERO) == 1) {
                MemberStoreBalance updateMemberStoreBalance = new MemberStoreBalance();
                updateMemberStoreBalance.setId(memberStoreBalanceVo.getId());
                updateMemberStoreBalance.setTotalPay(memberStoreBalance.getTotalPay().add(memberStoreBalanceVo.getTotalPay()));
                updateMemberStoreBalance.setVersionId(memberStoreBalanceVo.getVersionId());
                memberStoreBalanceCommonService.updateTotalPayById(updateMemberStoreBalance);
            }
        }
        /**将手机号重复的会员合并到当前登录的会员并将member_store_balance的累加-end*/


        // 删除相同手机号的member记录
        memberCommonDao.delete(member.getId());

        Member updateMember = new Member();
        updateMember.setId(currMember.getId());
        updateMember.setUnionId(member.getUnionId());
        updateMember.setOpenId(member.getOpenId());
        updateMember.setZfbUnionId(member.getZfbUnionId());
        updateMember.setZfbUserId(member.getZfbUserId());
        updateMember.setTtUnionId(member.getTtUnionId());
        updateMember.setTtOpenId(member.getTtOpenId());
        memberCommonDao.updateById(updateMember);

        return member.getId();
    }
}
